package com.zxx.otherchaos.widgets.rvtouch;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

import com.zxx.otherchaos.R;

import java.util.Collections;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @author zxx on 2022/1/19
 */
public class ItemRvAdapter extends RecyclerView.Adapter<ItemRvAdapter.MyViewHolder> implements ItemTouchHelperCallback.ItemTouchHelperAdapter {

    private List<String> list;

    public ItemRvAdapter(List<String> list) {
        this.list = list;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_touch_rv, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.textView.setText(list.get(position));
        holder.itemView.setAnimation(AnimationUtils.loadAnimation(holder.itemView.getContext(), R.anim.set_t_a_s));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public void onItemMove(int sourcePosition, int targetPosition) {
        Log.e("Tab--->", "移动：" + sourcePosition + " - " + targetPosition);

        //可能需要循环来交换顺序，否则数据混乱，这里只是简单处理，具体看打印日志
        Collections.swap(list, sourcePosition, targetPosition);
        notifyItemMoved(sourcePosition, targetPosition);
    }

    @Override
    public void onItemDismiss(int position) {
        Log.e("Tab--->", "删除：" + position);
        //仅仅用这一个数据混乱
        //notifyItemRemoved(position);

        list.remove(position);
        notifyItemRemoved(position);
        //notifyItemRangeChanged(position, list.size() - position);
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {
        TextView textView;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.item_text);
        }

        void onItemSelected(){
            Log.e("Tab--->","选择：");
        }

        void onItemClear(){
            Log.e("Tab--->","清空选择：");
        }
    }

}
